package com.library.picture.books.utils;

import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.*;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.*;

/**
 * PDF转图片
 *
 * @author wanghongjie
 */
public class PdfToPngUtils {

    public static void main(String[] args) throws IOException {
        convertToPNG("/Users/wanghongjie/Downloads/龟兔赛跑/龟兔赛跑.pdf");
    }

    private static void convertToPNG(String filePath) throws IOException {
        File targetFile = new File(filePath);
        String imageType = "jpg";
        try (PDDocument document = PDDocument.load(targetFile);
        ) {
            PDFRenderer renderer = new PDFRenderer(document);
            int pageSize = document.getNumberOfPages();
            for (int i = 0; i < pageSize; i++) {
                BufferedImage image = renderer.renderImage(i);
                File outputPath = getOutputPath(targetFile, imageType, i + 1);
                ImageIO.write(image, imageType, outputPath);
                FileInputStream inputStream = new FileInputStream(outputPath);
                byte[] bytes = scaleImage(inputStream, 0.8f, imageType);
                FileUtils.writeByteArrayToFile(outputPath, bytes);
            }
        }
    }

    private static File getOutputPath(File file, String imageType, int page) {
        String fullName = file.getName();
        String preName = new StringBuilder(fullName).substring(0, fullName.length() - 4);
        String parentPath = file.getParent();
        return new File(String.format("%s%s%s_%d.%s", parentPath, File.separator, preName, page, imageType));
    }

    /**
     * @param qality 压缩的程度
     * @param suffix 文件格式，pdf，jpg
     **/
    public static byte[] scaleImage(InputStream inputStream, float qality, String suffix) {
        BufferedImage bufferedImage;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageWriter imgWriter;
        ImageWriteParam imgWriteParams;
        try {
            bufferedImage = ImageIO.read(inputStream);
            imgWriter = ImageIO.getImageWritersByFormatName(suffix).next();
            imgWriteParams = new JPEGImageWriteParam(null);
            // 要使用压缩，必须指定压缩方式为MODE_EXPLICIT
            imgWriteParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            // 这里指定压缩的程度，参数qality是取值0~1范围内，
            imgWriteParams.setCompressionQuality(qality);
            imgWriteParams.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
            ColorModel colorModel = bufferedImage.getColorModel();
            imgWriteParams.setDestinationType(new ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(32, 32)));
            imgWriter.reset();
            // OutputStream构造
            imgWriter.setOutput(ImageIO.createImageOutputStream(out));
            imgWriter.write(null, new IIOImage(bufferedImage, null, null), imgWriteParams);
            return out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
